const express = require('express');
const multer = require('multer');
const moment = require('moment');
const router = express.Router();
let db = require("../db.js");




// **********************************************新增：下载包 专门处理formData  POST请求
// 2.1  multer: uploads自己后台规则路径（在项目根目录下）  npm i multer  
//      接受前端传递过来图片文件
const upload = multer({ dest: 'uploads/' });
// 2.2  为设计路径，专门配置中间件
//      识别发送请求 从哪个字段里面获取文件对象
router.post("/add", upload.single('cover_img'), function(req, res) {

  //  2.3 multer: 文件没有后缀！文件被改名！req.body
  //     经过上面中间件处理  req.file.filename 获取到上传后文件的名称（）；
  //     拼接路径地址：设置给req.body
  req.body.cover_img = "/uploads/" + req.file.filename;
  req.body.pub_date = moment().format("YYYY-MM-DD HH:mm:ss");
  req.body.author_id = req.user.id;

  db("select name from category where Id=?", req.body.cate_id, function(err, arr) {
    if (err) {
      res.send({
        status: 1,
        message: "查询数据库失败！",
      });
    }
    // 
    else {
      req.body.cate_name = arr[0].name;


      //  2.4 req.body对象 insert到数据库里面
      db("insert into article set ?", req.body, function(err, data) {
        if (err != null) {
          res.send({
            status: 1,
            message: "新增文章失败！",
          });
        } else {
          res.send({
            status: 0,
            message: "新增文章成功！",
          });
        }
      })
    }
  });





});




// ******************************************************************删除
router.get("/delete/:id", function(req, res) {
  // 1.获取id
  let Id = req.params.id;
  db("delete from article where Id=?", Id, function(err, obj) {
    if (err != null) {
      res.send({
        status: 1,
        message: "删除文章失败！",
      });
    } else {
      res.send({
        status: 0,
        message: "删除文章成功！"
      });
    }
  });
});




// ******************************************************************更新
router.post("/edit", upload.single('cover_img'), function(req, res) {
  // 若没有新的图片上传  req.file  ==undefined
  if (req.file) {
    req.body.cover_img = "/uploads/" + req.file.filename;
  }
  req.body.pub_date = moment().format("YYYY-MM-DD HH:mm:ss");
  req.body.author_id = req.user.id;

  db("select name from category where Id=?", req.body.cate_id, function(err, arr) {
    if (err) {
      res.send({
        status: 1,
        message: "查询数据库失败！",
      });
    }
    // 
    else {
      req.body.cate_name = arr[0].name;


      //  req.body对象 更新到数据库里面
      db("update article set ? where Id=?", [req.body, req.body.Id], function(err, data) {
        if (err != null) {
          res.send({
            status: 1,
            message: "更新文章失败！",
          });
        } else {
          res.send({
            status: 0,
            message: "更新文章成功！",
          });
        }
      })
    }
  });
});



// ******************************************************************列表
router.get("/list", function(req, res) {
  // 1.简单：GET  pagenum 页码  pagesize：要几条数据
  let m = req.query.pagenum;
  let n = req.query.pagesize;
  let cate_id = req.query.cate_id;
  let state = req.query.state;

  // 假设： cate_id=1  state  有什么用？
  // 结论： 查询条件不一样！会导致sql语句！
  // 解决：拼接
  let str = "";
  if (cate_id) {
    str += ` and cate_id=${cate_id}`;
  }
  if (state) { // 已发布字符串 两边加""
    str += ` and state="${state}"`;
  }

  // 查总数
  db(`select count(*) as total from article where author_id=? ${str}`, req.user.id, function(err, obj) {
    console.log(err);
    if (err != null) {
      res.send({
        status: 1,
        message: "获取文章失败！",
      });
    } else {
      // 查询 分页
      db(`select * from article where author_id=? ${str} limit ?,?`, [req.user.id, (m - 1) * n, n * 1], function(err, arr) {
        if (err != null) {
          res.send({
            status: 1,
            message: "获取文章失败！",
          });
        } else {
          res.send({
            status: 0,
            message: "获取文章成功！",
            data: arr,
            total: obj[0].total
          });
        }
      });
    }
  });



});


module.exports = router;